//
//  CHViewController.swift
//  status
//
//  Created by 彳亍 on 2017/3/22.
//  Copyright © 2017年 彳亍. All rights reserved.
//

import UIKit

class CHViewController: UIViewController {
    
    /// 列表视图如果没有登录则不创建
    var tableView : UITableView?
    /// 刷新控件
    var refreshControl:UIRefreshControl?
    /// 是否是上拉刷新
    var isPullUp:Bool = false
    
    /// 用户登录状态
    fileprivate var logan:Bool  {
        return CHHTTPSessionManager.shared.logan
    }
    /// 导航栏
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0,
                                                           y: 0,
                                                           width: UIScreen.main.bounds.width,
                                                           height: 64))
    ///UINavigationItem
    lazy var navItem = UINavigationItem()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 1. 设置UI
        setupUI()
        // 2. 设置导航栏
        setupNavigationBar()
        // 3.注册通知
        registerNotifications()
    }
    
    deinit {
        // 1.移除通知
        removeNotifications()
    }
    
    
    /// 游客信息
    var visitorInfo:[String:String]?
    /// 重写title
    override var title: String? {
        didSet {
            navItem.title = title
        }
    }
    
    /// 刷新数据
    @objc func loadData() {
        
        if isPullUp {
            
            print("上拉刷新")
            
            isPullUp = false
            
        }else {
            
            print("下拉刷新")
            
        }
        
        
        refreshControl?.endRefreshing()
    }
    
    
}

// MARK: - 设置通知
fileprivate extension CHViewController {
    
    /// 注册通知
    func registerNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(loginSuccessNotification),
                                               name: NSNotification.Name(rawValue: CHUserLoginSuccessNotification),
                                               object: nil)
    }
    
    /// 移除通知
    func removeNotifications() {
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 登录成功通知
    @objc func loginSuccessNotification() {
        //  在访问 view 的 getter 时，如果 view == nil 会调用 loadView -> viewDidLoad
        view = nil
        
        // 移除通知，防止重复注册
        removeNotifications()
    }
    
    
    
}

// MARK: - 监听方法
extension CHViewController {
    
    /// 注册
    @objc fileprivate func register() {
        print(#function)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: CHUserLoginNotification), object: nil)
    }
    
    /// 登录
    @objc fileprivate func login() {
        print(#function)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: CHUserRegisterNotification), object: nil)
    }
    
    /// 设置
    @objc fileprivate func setup() {
        print(#function)
    }
    
}

extension CHViewController:UITableViewDataSource,UITableViewDelegate {
    
    /// numberOfSections
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    /// numberOfRowsInSection
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    /// cellForRowAt
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = UITableViewCell()
        
        cell.backgroundColor = UIColor.ch_randomColor()
        
        return cell
    }
    
    /// heightForRowAt
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 60
    }
    
    
    /// 上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // 目的: 判断当前展示的是否是 最后一个cell
        
        // 1. 获取 组数
        let sectionCount = tableView.numberOfSections
        // 2. 判断是否是最后一组
        if  indexPath.section != sectionCount - 1 {
            return
        }
        
        // 3. 获取行数
        let rowCount = tableView.numberOfRows(inSection: indexPath.section)
        
        // 4. 判断是否是最后一行
        if indexPath.row != rowCount - 1 {
            return
        }
        
        // 5. 判断当前是否是上拉刷新
        if isPullUp == false {
            // 记录刷新状态
            isPullUp = true
            // 刷新数据
            loadData()
            
        }
    }
}

// MARK: - UI
extension CHViewController {
    
    /// 设置列表视图
    func setupTableView() {
        // 1.设置导航栏
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        // 2.创建列表视图
        tableView = UITableView(frame: UIScreen.main.bounds)
        // 3.添加列表视图
        view.insertSubview(tableView!, belowSubview: navigationBar)
        // 4. 设置tableView
        tableView!.delegate = self
        tableView!.dataSource = self
        
        tableView!.contentInset = UIEdgeInsets(top: navigationBar.bounds.height,
                                               left: 0,
                                               bottom: tabBarController?.tabBar.bounds.height ?? 49 ,
                                               right: 0)
        
        tableView!.scrollIndicatorInsets = tableView!.contentInset
        
        // 刷新控件
        refreshControl = UIRefreshControl()
        tableView!.addSubview(refreshControl!)
        refreshControl?.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
        
        
    }
    
    /// 设置访客试图
    private func setupVisitorView(){
        let type = type(of:self)
        switch type {
        case is CHHomeController.Type:
            // 1. 导航栏
            navItem.leftBarButtonItem = UIBarButtonItem(tilte: "注册", target: self, action: #selector(register))
            navItem.rightBarButtonItem = UIBarButtonItem(tilte: "登录", target: self, action: #selector(login))
            // 2. 访客视图
            let visitorView = CHHomeVisitorView(frame: UIScreen.main.bounds)
            view.insertSubview(visitorView, belowSubview: navigationBar)
            visitorView.visitorInfo = visitorInfo
            
            break
        case is CHMessageController.Type:
            // 2. 访客视图
            let visitorView = CHMessageVistorView(frame: UIScreen.main.bounds)
            view.insertSubview(visitorView, belowSubview: navigationBar)
            visitorView.visitorInfo = visitorInfo
            
            break
        case is CHDiscoverController.Type:
            // 1. 导航栏
            navItem.leftBarButtonItem = UIBarButtonItem(tilte: "注册", target: self, action: #selector(register))
            navItem.rightBarButtonItem = UIBarButtonItem(tilte: "登录", target: self, action: #selector(login))
            
            
            break
        case is CHProfileController.Type:
            // 1. 导航栏
            navItem.rightBarButtonItem = UIBarButtonItem(tilte: "设置",
                                                         titleColor:UIColor.darkGray,
                                                         target: self,
                                                         action: #selector(setup))
            // 2. 访客视图
            let visitorView = CHProfileVisitorView(frame: UIScreen.main.bounds)
            view.insertSubview(visitorView, belowSubview: navigationBar)
            visitorView.visitorInfo = visitorInfo
            
            break
            
        default: break
            
        }
        
    }
    
    /// 设置导航栏
    fileprivate func setupNavigationBar() {
        // 添加导航栏
        view.addSubview(navigationBar)
        navigationBar.items = [navItem]
        // 设置背景渲染色
        navigationBar.barTintColor = UIColor.ch_colorWithHex(hex: 0xF6F6F6)
        // 设置navibar 字体渲染色
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.darkGray]
        // 设置系统按钮渲染色
        navigationBar.tintColor = UIColor.orange
    }
    
    
    /// 设置UI
    fileprivate func setupUI() {
        // 1.背景色
        view.backgroundColor = UIColor.ch_colorWithHex(hex: 0xEDEDED)
        // 2. 列表视图/访客视图
        logan ? setupTableView() : setupVisitorView()
        // 3. 取消自动缩紧
        automaticallyAdjustsScrollViewInsets = false
        
    }
}





